package com.zqq.aidldemo.aidlServer;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.zqq.aidldemo.BooKCheckService;
import com.zqq.aidldemo.R;

/**
 * 利用studio自动生成的AIDL测试
 */
public class Main2Activity extends AppCompatActivity {

    private BooKCheckService kCheckService; //这个是AIDL


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        Intent intent = new Intent();
        //Android5.0中service的intent一定要显性声明【一种方法】
        intent.setAction("com.zqq.aidl.aidlserver");    //隐士意图

        //隐式调用是除了设置setAction()外，还需要设置setPackage();【另一种方法】
        intent.setPackage(this.getPackageName());

        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("*******************服务已经连接！！！");
            //获取BooKCheckService对象，然后在onClick中调用BooKCheckService.getName()。
            kCheckService = BooKCheckService.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("*******************服务关闭连接！！");
        }
    };

    /**
     * 通过隐式意图来绑定service，在onServiceConnected方法中通过BooKCheckService.Stub.asInterface(service)
     * 获取BooKCheckService对象，然后在onClick中调用BooKCheckService.getBookInfo()。
     */
    public void onClick(View view) {
        try {
            String name = kCheckService.getBookInfo("<此时>");
            String list = kCheckService.getBookList();

            Log.e("Tag-", name + "-" + list);
            Toast.makeText(this, name + "-" + list, Toast.LENGTH_SHORT).show();

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }
}
